import { existsSync } from 'fs';
import { mkdir } from 'fs/promises';
import { SetTimeoutThread } from 'lite-ts-thread';
import { fromFile } from 'psd';
import { basename, extname, join } from 'path';

import { ConverterFactory, EditorAssertService, FsFileFactory } from './service';

export const methods = {
    async convert(psdFile: string, view: string) {
        const psd = fromFile(psdFile);
        psd.parse();

        if (!view) {
            const ext = extname(psdFile);
            view = basename(
                psdFile.replace(ext, '')
            ).split('_').join('/');
        }

        const fileFactory = new FsFileFactory(
            join(__dirname, '..', '..', '..', '..', 'assets'),
            view,
        );
        const pathArgs = view.split('/');
        pathArgs.push('texture');
        let dirPath = fileFactory.cwd;
        for (const r of pathArgs) {
            dirPath = join(dirPath, r);
            const isExist = existsSync(dirPath);
            if (isExist)
                continue;

            await mkdir(dirPath);
        }

        const thread = new SetTimeoutThread();
        const assetService = new EditorAssertService(view);
        const treePSD = psd.tree();
        const canvas = await new ConverterFactory(
            assetService,
            fileFactory,
            thread,
            treePSD.get<number>('width') / 2,
            treePSD.get<number>('height') / 2,
        ).build(treePSD).convert();

        const content = cce.Prefab.generatePrefabDataFromNode(canvas);
        await Editor.Message.request('asset-db', 'create-asset', `${assetService.cwd}/canvas.prefab`, content, {
            overwrite: true
        });
    },
};